package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;

import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public UserVo login(LoginDto loginDto) {
        //查询用户返回用户信息
        User user =userMapper.selectByName(loginDto.getUsername());
        //判断用户是否存在如果userVo为空，则该方法返回true，反之返回false
        if(ObjectUtil.isEmpty(user)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //账号是否被禁用
        if(user.getDataState().equals(SuperConstant.DATA_STATE_1)){
            throw new BaseException(BasicEnum.ACCOUNT_DISABLE);
        }
        //密码是否正确
        if(!BCrypt.checkpw(loginDto.getPassword(), user.getPassword())){
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        //对象的转换
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        //密码脱敏
        userVo.setPassword("");
        //从数据库中根据用户id--角色--资源
        List<String> resourcePaths = resourceMapper.selectListByUserId(userVo.getId());
        //获取白名单数据
        List<String> whiteList = securityConfigProperties.getPublicAccessUrls();
        //合并数据
        resourcePaths.addAll(whiteList);

        //共享数据
        Map map=new HashMap<String,Object>();
        map.put("currentUser", JSONUtil.toJsonStr(userVo));
        //生成jwt
        String jwt = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(), map);
        //超时时间
        long ttl = Long.parseLong(jwtTokenManagerProperties.getTtl().toString()) / 1000;
        //把资源路径存放到redis
        redisTemplate.opsForValue().set(CacheConstant.PUBLIC_ACCESS_URLS+userVo.getId(),
                JSONUtil.toJsonStr(resourcePaths),ttl, TimeUnit.SECONDS);
        userVo.setUserToken(jwt);

        return userVo;
    }
}
